package com.ruoyi.business.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.business.domain.ZrsDfAnnex;
import com.ruoyi.business.domain.ZrsDfGoal;
import com.ruoyi.business.domain.ZrsDfMain;
import com.ruoyi.business.domain.ZrsDfZbFslog;
import com.ruoyi.business.domain.zrsdfzb.ZrsGlxYjzb;
import com.ruoyi.business.service.IZrsDfAnnexService;
import com.ruoyi.business.service.IZrsDfMainService;
import com.ruoyi.business.service.IZrsMbManageService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;

/**
 * 责任书打分Controller
 * 
 * @author Yuhf
 * @date 2023-12-03
 */
@RestController
@RequestMapping("/business/ZrsDfMain")
public class ZrsDfMainController extends BaseController
{
    @Autowired
    private IZrsDfMainService zrsDfMainService;
    @Autowired
    private IZrsMbManageService zrsMbManageService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IZrsDfAnnexService zrsDfAnnexService;
    
    private static final String FILE_DELIMETER = ",";
    /**
     * 查询责任书打分列表
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:list')")
    @GetMapping("/deptList")
    public TableDataInfo deptList(ZrsDfMain zrsDfMain)
    {
        startPage();
        List<ZrsDfMain> list = zrsDfMainService.selectZrsDfMainDeptList(zrsDfMain);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:list')")
    @GetMapping("/userList")
    public TableDataInfo userList(ZrsDfMain zrsDfMain)
    {
        startPage();
        List<ZrsDfMain> list = zrsDfMainService.selectZrsDfMainUserList(zrsDfMain);
        return getDataTable(list);
    }
    
    
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:list')")
    @GetMapping("/listZrsDf")
    public TableDataInfo listZrsDf(ZrsDfMain zrsDfMain)
    {
        startPage();
        if(!getLoginUser().getUser().isAdmin()) {
        	zrsDfMain.setDfDeptId(getDeptId());//当前部门  
        }
        List<ZrsDfMain> list = zrsDfMainService.selectZrsDfDeptList(zrsDfMain);
        return getDataTable(list);
    }
    /**
     * 获取责任书打分详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:query')")
    @GetMapping(value = "/{zrsMainId}")
    public AjaxResult getInfo(@PathVariable("zrsMainId") Long zrsMainId)
    {
        return success(zrsDfMainService.selectZrsDfMainByZrsMainId(zrsMainId));
    }
    
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:edit')")
    @Log(title = "责任书汇算", businessType = BusinessType.UPDATE)
    @PostMapping("/settleZrsDf")
    public AjaxResult settleZrsDf(@RequestBody ZrsDfMain zrsDfMain){
    	
    	zrsDfMain.setCreateBy(getUsername());
    	zrsDfMain.setCreateTime(DateUtils.getNowDate());
    	if(StringUtils.isNotEmpty(zrsDfMain.getZrsKhdateStr())){
    		zrsDfMain.setZrsKhdate(DateUtils.parseDate(zrsDfMain.getZrsKhdateStr()+"-01"));
    	}else {
    		zrsDfMain.setZrsKhdate(DateUtils.getNowDate());
    	}
    	return AjaxResult.success(zrsDfMainService.settleZrsDf(zrsDfMain));
    }
    /**
     * 获取责任书打分详细信息
     * 打分指标详情  等
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:query')")
    @GetMapping(value = "/getZrsDfZbInfo/{zrsMainId}")
    public AjaxResult getZrsDfZbInfo(@PathVariable("zrsMainId") Long zrsMainId)
    {
    	Map<String, Object> date = new HashMap<String, Object>();
    	date.put("zrsDfInfo", zrsDfMainService.selectZrsDfMainByZrsMainId(zrsMainId));//打分info
    	date.put("shDeptInfo", zrsMbManageService.selectZbManageShDeptAll());//审核部门对象
    	
    	//查询 打分管理项 通过考核部门 进行查询
    	ZrsDfGoal zrsDfGoal = new ZrsDfGoal();
    	ZrsDfAnnex zrsDfAnnex = new ZrsDfAnnex();
    	if(!getLoginUser().getUser().isAdmin()) {
    		zrsDfGoal.setDfDeptId(getDeptId());//当前部门 
    		zrsDfAnnex.setUploadDeptId(getDeptId());
        }
    	zrsDfGoal.setZrsMainId(zrsMainId);
    	zrsDfAnnex.setZrsMainId(zrsMainId);
    	
        List<ZrsDfGoal> list = zrsDfMainService.selectZrsDfMainGoalList(zrsDfGoal);
        for (ZrsDfGoal zrsDfGoal2 : list) {
        	zrsDfGoal.setMbGoalId(zrsDfGoal2.getMbGoalId());
        	zrsDfAnnex.setZrsGlxId(zrsDfGoal2.getMbGoalId());
        	//查询管理项指标
        	List<ZrsGlxYjzb> dfGlxZbList = zrsDfMainService.selectZrsDfMainGoalZbListObj(zrsDfGoal);
        	if(!dfGlxZbList.isEmpty()) {
        		date.put("glx_zblist_"+zrsDfGoal2.getMbGoalId().toString(), dfGlxZbList);
        	}
        	//查询  管理项附件
        	List<ZrsDfAnnex> zrsDfAnnexList = zrsDfAnnexService.selectZrsDfAnnexList(zrsDfAnnex);
        	if(!zrsDfAnnexList.isEmpty()) {
        		List<Map> fileList = new ArrayList<Map>();
                Map fileMap = null;
        		for (ZrsDfAnnex zrsDfAnnex1 : zrsDfAnnexList) {
        			fileMap = new HashMap();
        			fileMap.put("annexId", zrsDfAnnex1.getAnnexId());
        			fileMap.put("glxId", zrsDfGoal2.getMbGoalId());
                    fileMap.put("name", zrsDfAnnex1.getFileName());
                    fileMap.put("status", "success");
                    fileMap.put("url", zrsDfAnnex1.getFileUrl());
                    fileList.add(fileMap);
				}
        		date.put("glx_filelist_"+zrsDfGoal2.getMbGoalId().toString(), fileList);
        	}
		}
        date.put("mbGlxList", list);
    	
        return AjaxResult.success(date);
    }
    //删除附件
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:edit')")
    @Log(title = "责任书附件删除", businessType = BusinessType.DELETE)
    @GetMapping(value = "/delZrsFile/{annexId}")
    public AjaxResult delZrsFile(@PathVariable("annexId") Long annexId){
    	ZrsDfAnnex zrsDfAnnex = new ZrsDfAnnex();
    	zrsDfAnnex.setDelBy(getUsername());
    	zrsDfAnnex.setDelTime(DateUtils.getNowDate());
    	zrsDfAnnex.setDelFlag("2");
    	zrsDfAnnex.setAnnexId(annexId);
    	
    	ZrsDfAnnex zrsDfAnnex2 = zrsDfAnnexService.selectZrsDfAnnexByAnnexId(annexId);
    	zrsDfAnnexService.updateZrsDfAnnex(zrsDfAnnex);
    	
    	ZrsDfAnnex newZrsDfAnnex2 = new ZrsDfAnnex();
    	if(!getLoginUser().getUser().isAdmin()) {
    		newZrsDfAnnex2.setUploadDeptId(getDeptId());
        }
    	newZrsDfAnnex2.setZrsMainId(zrsDfAnnex2.getZrsMainId());
    	newZrsDfAnnex2.setZrsGlxId(zrsDfAnnex2.getZrsGlxId());
    	//查询  管理项附件
    	List<ZrsDfAnnex> zrsDfAnnexList = zrsDfAnnexService.selectZrsDfAnnexList(newZrsDfAnnex2);
    	if(!zrsDfAnnexList.isEmpty()) {
    		List<Map> fileList = new ArrayList<Map>();
            Map fileMap = null;
    		for (ZrsDfAnnex zrsDfAnnex1 : zrsDfAnnexList) {
    			fileMap = new HashMap();
    			fileMap.put("annexId", zrsDfAnnex1.getAnnexId());
    			fileMap.put("glxId", zrsDfAnnex2.getZrsGlxId());
                fileMap.put("name", zrsDfAnnex1.getFileName());
                fileMap.put("status", "success");
                fileMap.put("url", zrsDfAnnex1.getFileUrl());
                fileList.add(fileMap);
			}
    		return AjaxResult.success(fileList);
    	}
    	return AjaxResult.success();
    }
    /**
     * 保存指标打分
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:edit')")
    @Log(title = "保存打分指标", businessType = BusinessType.UPDATE)
    @PostMapping("/saveZrsDf")
    public AjaxResult saveZrsDf(@RequestBody ZrsDfZbFslog zrsDfZbFslog){
    	
    	zrsDfZbFslog.setCreateBy(getUsername());
    	zrsDfZbFslog.setUpdateBy(getUsername());
    	zrsDfZbFslog.setCreateTime(DateUtils.getNowDate());
    	zrsDfZbFslog.setUpdateTime(DateUtils.getNowDate());
    	return toAjax(zrsDfMainService.saveZrsDf(zrsDfZbFslog));
    }
    /**
     * 保存指标打分 -- 一票否决
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:edit')")
    @Log(title = "保存打分指标[一票否决]", businessType = BusinessType.UPDATE)
    @PostMapping("/saveZrsDfVeto")
    public AjaxResult saveZrsDfVeto(@RequestBody ZrsDfZbFslog zrsDfZbFslog){
    	
    	zrsDfZbFslog.setCreateBy(getUsername());
    	zrsDfZbFslog.setUpdateBy(getUsername());
    	zrsDfZbFslog.setCreateTime(DateUtils.getNowDate());
    	zrsDfZbFslog.setUpdateTime(DateUtils.getNowDate());
    	return toAjax(zrsDfMainService.saveZrsDfVeto(zrsDfZbFslog));
    }
    
    /**
     * 修改责任书打分
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:edit')")
    @Log(title = "责任书打分", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZrsDfMain zrsDfMain)
    {
    	
    	zrsDfMain.setUpdateTime(DateUtils.getNowDate());
    	zrsDfMain.setUpdateBy(getUsername());
        return toAjax(zrsDfMainService.updateZrsDfMain(zrsDfMain));
    }
    /**
     * 责任书  附件上传
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:edit')")
    @Log(title = "责任书附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(MultipartFile[] files,Long zrsId,Long glxId) throws Exception
    {
        try
        {
        	if(!getLoginUser().getUser().isAdmin()) {
        		//getDeptId();//当前部门  
            }
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            SysUser userInfo = getLoginUser().getUser();
            List<Map> fileList = new ArrayList<Map>();
            Map fileMap = null;
            //插入数据库 
            ZrsDfAnnex zrsDfAnnex = null;
            for (MultipartFile file : files){
            	fileMap = new HashMap();
            	// 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
                
            	zrsDfAnnex = new ZrsDfAnnex();
            	zrsDfAnnex.setZrsMainId(zrsId);
            	zrsDfAnnex.setZrsGlxId(glxId);
            	zrsDfAnnex.setUploadDeptId(getDeptId());
            	zrsDfAnnex.setUploadDeptName(userInfo.getDept().getDeptName());
            	zrsDfAnnex.setUploadUserId(getUserId());
            	zrsDfAnnex.setUploadUserName(userInfo.getNickName());
            	zrsDfAnnex.setFileName(file.getOriginalFilename());
            	zrsDfAnnex.setFileUrl(fileName);
            	zrsDfAnnex.setCreateTime(DateUtils.getNowDate());
            	zrsDfAnnex.setCreateBy(getUsername());
                zrsDfAnnexService.insertZrsDfAnnex(zrsDfAnnex);
                fileMap.put("annexId", zrsDfAnnex.getAnnexId());
                fileMap.put("glxId", glxId);
                fileMap.put("name", file.getOriginalFilename());
                fileMap.put("status", "success");
                fileMap.put("url", fileName);
                fileList.add(fileMap);
            }
//            AjaxResult ajax = AjaxResult.success();
//            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
//            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
//            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
//            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
//            fileNames "/profile/upload/2023/12/12/新建 文本文档 (2)_20231212174112A001.txt,/profile/upload/2023/12/12/新建 文本文档_20231212174112A002.txt"
//            newFileNames "新建 文本文档 (2)_20231212174112A001.txt,新建 文本文档_20231212174112A002.txt"
//            originalFilenames "新建 文本文档 (2).txt,新建 文本文档.txt"
//            urls "http://localhost:8086/profile/upload/2023/12/12/新建 文本文档 (2)_20231212174112A001.txt,http://localhost:8086/profile/upload/2023/12/12/新建 文本文档_20231212174112A002.txt"
//            return ajax;
            return AjaxResult.success(fileList);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 删除责任书打分
     */
    @PreAuthorize("@ss.hasPermi('business:ZrsDfMain:remove')")
    @Log(title = "责任书打分", businessType = BusinessType.DELETE)
	@DeleteMapping("/{zrsMainId}")
    public AjaxResult remove(@PathVariable Long zrsMainId)
    {
    	ZrsDfMain zrsDfMain = new ZrsDfMain();
    	zrsDfMain.setDelTime(DateUtils.getNowDate());
    	zrsDfMain.setDelBy(getUsername());
    	zrsDfMain.setZrsMainId(zrsMainId);
        return toAjax(zrsDfMainService.updateZrsDfMain(zrsDfMain));
    }
}
